// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const TcbRouter = require('tcb-router')
const db = cloud.database()
const itemCollection = db.collection('campus')
const userCollection = db.collection('student')

const MAX_LIMIT = 100
// 云函数入口函数
exports.main = async (event, context) => {
  const openid = event.userInfo.openId
  const itemId = event.itemId
  const app = new TcbRouter({
    event
  })
  app.router('list', async (ctx, next) => {
    const {
      _class,
      subClass,
      keyword
    } = event
    let w = {
      reportNum: db.command.lt(20)
    }
    if (_class && _class > 0) {
      w.class = _class
    }
    if (subClass && subClass > 0) {
      w.subClass = subClass
    }
    if (keyword) {
      w.content = db.RegExp({
        regexp: keyword,
        options: 'i' //可以忽略大小写
      })
    }
    let itemList = await itemCollection.where(w).orderBy('createTime', 'desc')
      .skip(event.start).limit(event.count).get()
      .then((res) => {
        return res.data
      })
    ctx.body = itemList
  })

  app.router('watch', async (ctx, next) => {
    await itemCollection.doc(itemId).update({
      data: {
        watchNum: db.command.inc(1)
      }
    })
  })

  app.router('over', async (ctx, next) => {
    const res = await itemCollection.doc(itemId).update({
      data: {
        ifComplete: true
      }
    })
    ctx.body = {
      res
    }
  })

  app.router('delete', async (ctx, next) => {
    const res = await itemCollection.doc(itemId).remove()
    ctx.body = {
      res
    }
  })

  app.router('like', async (ctx, next) => {
    let res1 = '',
      res2 = ''
    if (event.ifLike) {
      res1 = await itemCollection.doc(itemId).update({
        data: {
          likeNum: db.command.inc(-1)
        }
      })
      res2 = await userCollection.where({
        _openid: openid
      }).update({
        data: {
          like: db.command.pull(itemId)
        }
      })
    } else {
      res1 = await itemCollection.doc(itemId).update({
        data: {
          likeNum: db.command.inc(1)
        }
      })
      res2 = await userCollection.where({
        _openid: openid
      }).update({
        data: {
          like: db.command.addToSet(itemId)
        }
      })
    }
    ctx.body = {
      res1,
      res2
    }
  })

  app.router('report', async (ctx, next) => {
    let updated = (await userCollection.where({
      _openid: openid
    }).update({
      data: {
        report: db.command.addToSet(itemId)
      }
    })).stats.updated
    if (updated == 1) {
      await itemCollection.doc(itemId).update({
        data: {
          reportNum: db.command.inc(1)
        }
      })
    }
    ctx.body = {
      ifReportedBefore: updated==0
    }
  })
  return app.serve()
}